import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Before;
import org.junit.Test;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * 代码生成器
 */
public class MpGenerator {

    private DataSourceConfig dsc;

    private String projectPath;

    @Test
    public void generator() {

        String author = "R.hao";
        String[] tables = {"crawler_dom"};
        String[] tablePrefixs = {"t_"};

        generator(author, tablePrefixs, tables);
    }


    @Before
    public void before() {

        projectPath = System.getProperty("user.dir");
        try {
            //读取数据源
            InputStream is = new BufferedInputStream(new FileInputStream(projectPath + "/src/main/resources/application.properties"));
            Properties properties = new Properties();
            properties.load(new InputStreamReader(is, "UTF-8"));
            // 数据源配置
            dsc = new DataSourceConfig();
            dsc.setDbType(DbType.MYSQL);
            dsc.setDriverName(properties.getProperty("jdbc.driverClassName"));
            dsc.setUrl(properties.getProperty("jdbc.url"));
            dsc.setUsername(properties.getProperty("jdbc.username"));
            dsc.setPassword(properties.getProperty("jdbc.password"));
        } catch (Exception e) {
            System.err.println("不能读取属性文件.请确保application.properties在CLASSPATH指定的路径中");
        }
    }


    private void generator(String author, String[] tablePrefixs, String[] tables) {
        // 全局配置
        AutoGenerator mpg = new AutoGenerator();
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);
        gc.setEnableCache(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        gc.setServiceName("%sService");
        gc.setAuthor(author);
        mpg.setGlobalConfig(gc);

        //设置数据源
        mpg.setDataSource(dsc);

        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(tablePrefixs);
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setInclude(tables);
        mpg.setStrategy(strategy);

        PackageConfig pc = new PackageConfig();
        pc.setParent("com.hao");
        mpg.setPackageInfo(pc);

        TemplateConfig tc = new TemplateConfig();
        tc.setController(null);
        mpg.setTemplate(tc);

        mpg.execute();
    }
}